<?php
/**
 * Created by Jasmine.
 * Date: 2016/5/30
 * description:积分抽奖
 * Address: 浙江宣逸网络科技有限公司
 */

namespace Common\Model;
class PointLotteryModel extends BaseModel{
    //抽奖类型
    const POINTLOTTERY_TIMING     =1;//定时抽奖
    const POINTLOTTERY_FULL       =2;//满员抽奖

    //上线状态
    const LOTTERY_ALL      =0;//全部
    const LOTTERY_ONLINE   =1;//进行中
    const LOTTERY_PREPARE  =2;//待上线
    const LOTTERY_FINISH   =3;//已下线
    //抽奖结果
    const LOTTERY_RESULT_WIN    =2;//恭喜中奖
    const LOTTERY_RESULT_OUT    =1;//谢谢参与
    const LOTTERY_RESULT_WAIT   =0;//待开奖

    //管理员控制位，上线状态
    const POINTLOTTERY_IS_ONLINE  =1;//已经上线
    const POINTLOTTERY_IS_PREPARE =2;//未上线

    //活动是否已开奖
    const POINT_LOTTERY_ON_RESULT = 1;//已开奖
    const POINT_LOTTERY_NO_RESULT = 0;//未开奖
    /**
     * 获取积分抽奖列表信息
     * User: wwl<wuwl@soe-soe.com>
     * Return: void
     * Address: 浙江宣逸网络科技有限公司
     */
    public static function getLotteryList($uid,$status,$page,$pageSize){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        $dataSuccess['page'] = $page ? $page :1;          //返回当前页
        $offset = ($dataSuccess['page']-1)*$pageSize;     //起始条数

        $lotteryM = M('point_lottery',null,DB_MAIN_CFG);
        $nowTime = time();
        $where="1"; $order="period DESC,finishType ASC,";
        switch($status){
            case self::LOTTERY_PREPARE:
                $where .=" and {$nowTime} between beginShowTimestamp and beginTime";
                $order .= " beginTime ASC";
                break;
            case self::LOTTERY_ONLINE:
                $where .=" and (({$nowTime} between beginTime and endTime and finishType=".self::POINTLOTTERY_TIMING.") or (finishType=".self::POINTLOTTERY_FULL." and {$nowTime} between beginTime and endTime and joinPeople < fullNumber))";
                $order .= " endTime ASC";
                break;
            case self::LOTTERY_FINISH:
                $where .=" and (({$nowTime} >= endTime) or (finishType=".self::POINTLOTTERY_FULL." and joinPeople >= fullNumber))";
                $order .= " endTime DESC";
                break;
        }
        $lotteryInfo = $lotteryM->where($where)->order($order)->limit($offset,$pageSize)->select();
        $len = count($lotteryInfo)-1;

        for($i = $len;$i>0;$i--){
            if($lotteryInfo[$i]['finishType'] == $lotteryInfo[$i-1]['finishType']){
                if($lotteryInfo[$i]['period'] == $lotteryInfo[$i-1]['period']){
                    $lotteryInfo[$i]['period']="";
                }
            }
        }
        //中奖名单
        if($status == self::LOTTERY_FINISH){
            $hitId=array();
            foreach($lotteryInfo as $key => $val){
                $hitId[] = $val['id'];
            }
            if($hitId){
                $hitId = implode(',',$hitId);
                $hitUid = M('point_lottery_join',null,DB_MAIN_CFG)->where("result=".self::LOTTERY_RESULT_WIN." and lotteryID IN ({$hitId}) ")->field('lotteryID,uid,nickname,bindPhone')->select();
                if($hitUid){
                    foreach ($hitUid as $key => $val){
                        foreach ($lotteryInfo as $k=>$v){
                            if($val['lotteryID'] == $v['id']){
                                $lotteryInfo[$k]['userInfo'][$key]['nickname'] = mb_substr($val['nickname'],0,2,'utf-8').'**';
                                $lotteryInfo[$k]['userInfo'][$key]['bindPhone'] = substr_replace($val['bindPhone'],'****',3,4);
                            }
                        }
                    }
                }
            }
        }

        //是否已参与
        if($uid && $lotteryInfo){
            $idArr = array();
            foreach ($lotteryInfo as $key => $val){
                $idArr[] = $val['id'];
                $lotteryInfo[$key]['hasJoined'] = 0;
            }
            $idStr = implode(',',$idArr);
            $joinInfo = M('point_lottery_join',null,DB_MAIN_CFG)->where("lotteryID IN ({$idStr}) and uid={$uid}")->getField("lotteryID,uid");
            foreach ($lotteryInfo as $k=>$v){
                foreach ($joinInfo as $key => $val){
                    if($key == $v['id']){
                        $lotteryInfo[$k]['hasJoined'] = 1;
                        break;
                    }
                }
            }
        }

        $dataSuccess['list']=$lotteryInfo;
        $dataSuccess['total'] = $lotteryM->where($where)->count();        //获取数据总条数
        $dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);  //总页数
        $dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage']? 0:1;    //是否还有下一页
        return $dataSuccess;
    }

    //积分抽奖活动详情
    public static function getLotteryData($id,$status=0,$uid=0){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        if(!$id){
            return $dataFailure;
        }
        $lotteryM = M('point_lottery',null,DB_MAIN_CFG);
        $lotteryData = $lotteryM->where("id={$id}")->find();
        if(!$lotteryData){
            $dataFailure['msg']="抱歉，该活动已删除";
            return $dataFailure;
        }
        if($status == self::LOTTERY_ONLINE){
            //判断该用户是否参与该活动
            $dataSuccess['flag'] = M('point_lottery_join',null,DB_MAIN_CFG)->where("uid={$uid} and lotteryID=$id")->find()?1:0;
        }

        if($status == self::LOTTERY_FINISH){
            //获取中奖人信息
            $uidInfo = M('point_lottery_join',null,DB_MAIN_CFG)->where("lotteryID={$id} and result=".self::LOTTERY_RESULT_WIN)->field('uid,nickname,bindPhone')->select();
            if($uidInfo){
                foreach($uidInfo as $key => $val){
                    $lotteryData['userInfo'][$key]['uid'] = $val['uid'];
                    $lotteryData['userInfo'][$key]['nickname'] = mb_substr($val['nickname'],0,2,'utf-8').'**';
                    $lotteryData['userInfo'][$key]['bindPhone'] = substr_replace($val['bindPhone'],'****',3,4);
                }
            }
        }

        $dataSuccess['data']=$lotteryData;
        return $dataSuccess;
    }

    //定时积分抽奖
    public static function timingExchange($uid,$type,$lotteryID,$exchangeNum,$requirePoint){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        if(!$uid){
            return $dataFailure;
        }
        $userInfo = M('u_user_base',null,DB_MAIN_CFG)->where("uid={$uid}")->field('nickname,realName,bindPhone')->find();

        $nowTime=time();
        $lotteryType = M('point_lottery',null,DB_MAIN_CFG)->where("id={$lotteryID}")->getField("prizeType");
        $data = array(
            'uid'           => $uid,
            'nickname'      => $userInfo['nickname'],
            'realName'      => $userInfo['realName'],
            'bindPhone'     => $userInfo['bindPhone'],
            'type'          => $type,
            'lotteryID'     => $lotteryID,
            'prizeType'     => $lotteryType,
            'exchangeNum'   => $exchangeNum,
            'addTime'       => $nowTime,
            'costPoint'     => $requirePoint
        );

        $joinM = M('point_lottery_join',null,DB_MAIN_CFG);
//        if($joinM->where("uid={$data['uid']} and lotteryID={$data['lotteryID']}")->find()){
//            $dataFailure['msg']="sorry,您已参加过该抽奖活动，去看看别的吧^^";
//            return $dataFailure;
//        }
        $tmpR = UserModel::minusPoint($uid,-1,$requirePoint,OPT_FIX_LOTTERY,$lotteryID);
        if($tmpR['status']==0){
            //参与人数和参与次数
            $lotteryM = M('point_lottery',null,DB_MAIN_CFG);
            $joinInfo = $lotteryM->where("id={$lotteryID}")->field('title,joinTimes,joinPeople')->find();
            if($joinInfo){
                //保存参与记录
                $data['title'] = $joinInfo['title'];
                $data['costPoint'] = $requirePoint;
                $res = $joinM->add($data);
                if($res===false){
                    $dataFailure['msg']="活动参与失败";
                    return $dataFailure;
                }

                $lotteryM->where("id={$lotteryID}")->save(
                    array(
                        'joinPeople'  => $joinInfo['joinPeople']+1,
                        'joinTimes'   => $joinInfo['joinTimes']+$exchangeNum,
                    )
                );


                $dataSuccess['msg']="恭喜您，参与成功";
                return $dataSuccess;
            } else{
                $dataFailure['msg'] = "活动不存在";
                return $dataFailure;
            }

        }
        $dataFailure['msg']=$tmpR['msg'];
        return $dataFailure;
    }

    //满员积分抽奖
    public static function fullExchange($uid,$type,$lotteryID,$exchangeNum,$requirePoint){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        if(!$uid){
            return $dataFailure;
        }
        $userInfo = M('u_user_base',null,DB_MAIN_CFG)->where("uid={$uid}")->field('nickname,realName,bindPhone')->find();

        $nowTime=time();
        $lotteryType = M('point_lottery',null,DB_MAIN_CFG)->where("id={$lotteryID}")->getField("prizeType");
        $data = array(
            'uid'           => $uid,
            'nickname'      => $userInfo['nickname'],
            'realName'      => $userInfo['realName'],
            'bindPhone'     => $userInfo['bindPhone'],
            'type'          => $type,
            'lotteryID'     => $lotteryID,
            'prizeType'     => $lotteryType,
            'exchangeNum'   => $exchangeNum,
            'addTime'       => $nowTime,
            'result'        => PointLotteryModel::LOTTERY_RESULT_WAIT,
            'costPoint'     => $requirePoint
        );
        $joinM = M('point_lottery_join',null,DB_MAIN_CFG);
        $lotteryM = M('point_lottery',null,DB_MAIN_CFG);
//        if($joinM->where("uid=$uid and lotteryID=$lotteryID")->find()){
//            $dataFailure['msg']="sorry,您已参加过该抽奖活动，去看看别的吧^^";
//            return $dataFailure;
//        }
        $info = $lotteryM->where("id={$lotteryID}")->find();
        if($info['joinPeople'] < $info['fullNumber']){
            $tmpR = UserModel::minusPoint($uid,-1,$requirePoint,OPT_FULL_LOTTERY,$lotteryID);
            if($tmpR['status']==0){
                //保存兑换记录
                $data['title'] = $info['title'];
                $res = $joinM->add($data);
                if($res===false){
                    $dataFailure['msg']="活动参与失败";
                    return $dataFailure;
                }
                //参与人数和参与次数
                $infoData =  array(
                    'joinPeople'  => $info['joinPeople']+1,
                    'joinTimes'   => $info['joinTimes']+$exchangeNum,
                );
                $lotteryM->where("id={$lotteryID}")->save($infoData);
                $dataSuccess['msg']="恭喜您，参与成功";

                if($infoData['joinPeople'] >= $info['fullNumber']){
                    $joinM->where("lotteryID={$lotteryID} and uid != 0")->setField('result',self::LOTTERY_RESULT_OUT);
                    self::lotteryMethod($lotteryID);
                    $dataSuccess['fullMember']=1;
                }
                return $dataSuccess;
            }
            $dataFailure['msg']=$tmpR['msg'];
            return $dataFailure;
        }
        $dataFailure['msg']="您来晚咯,该活动已满额";
        return $dataFailure;
    }

    //我的抽奖记录
    public static function myRecord($uid,$page,$pageSize){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        if(!$uid){
            $dataFailure['msg']="请登录后操作";
            return $dataFailure;
        }

        $dataSuccess['page'] = $page ? $page :1;          //返回当前页
        $offset = ($dataSuccess['page']-1)*$pageSize;     //起始条数

        $joinM = M('point_lottery_join',null,DB_MAIN_CFG);

        $data = $joinM->where("uid={$uid}")->order('addTime desc')->limit($offset,$pageSize)->select();

        foreach($data as $key => $val){
            if($val['result']==self::LOTTERY_RESULT_WAIT){
                $data[$key]['result']="待开奖";
            }else if($val['result']==self::LOTTERY_RESULT_OUT){
                $data[$key]['result']="谢谢参与";
            }else if($val['result']==self::LOTTERY_RESULT_WIN){
                $data[$key]['result']="恭喜中奖";
            }
        }
        $info = $joinM->join("left join point_lottery as jo on jo.id=point_lottery_join.lotteryID")->where("point_lottery_join.uid={$uid}")->order('addTime desc')->limit($offset,$pageSize)->field('title,points')->select();

        foreach($info as $k => $v){
            $data[$k]['title'] = $v['title'];
            $data[$k]['points']= $data[$k]['exchangeNum']*$v['points'];
        }

        $dataSuccess['data']=$data;
        $dataSuccess['total'] = $joinM->where("uid={$uid}")->count();        //获取数据总条数
        $dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);      //总页数
        $dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage']?0:1;    //是否还有下一页
        return $dataSuccess;
    }

    //判断活动是否结束
    public static function isEnd($lotteryID=0){
        $nowTime = time();
        $lotteryM = M('point_lottery',null,DB_MAIN_CFG);

        $info = $lotteryM->where("id={$lotteryID}")->field('endTime')->find();
        if($nowTime >= $info['endTime']){
            self::lotteryMethod($lotteryID);
            return 0;
        } else return 1;

    }

    //判断已结束活动是否已抽奖
    public static function doLottery(){
        $now = time();
        $lotteryList = M('point_lottery',null,DB_MAIN_CFG)
            ->where("resultStatus=".self::POINT_LOTTERY_NO_RESULT." and (({$now} >= endTime) or (finishType=".self::POINTLOTTERY_FULL." and joinPeople >= fullNumber))")
            ->order("endTime DESC")
            ->field('id,endTime')
            ->select();
        if($lotteryList){
            foreach ($lotteryList as $val){
                self::lotteryMethod($val['id']);
            }
        }else{
            return true;
        }
    }

    //抽奖机制
    public static function lotteryMethod($lotteryID=0){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        if(!$lotteryID || $lotteryID <=0){
            return $dataFailure;
        }
        $lotteryM =  M('point_lottery',null,DB_MAIN_CFG);
        $lotteryInfo = $lotteryM->where("id={$lotteryID}")->find();
        if(!$lotteryInfo){
            return $dataFailure;
        }
        //活动是否已开奖
        if($lotteryInfo['resultStatus'] == self::POINT_LOTTERY_ON_RESULT){
            return $dataFailure;
        }
        $joinM = M('point_lottery_join',null,DB_MAIN_CFG);
        //将活动报名用户标志为未中奖
        $joinM->where("lotteryID={$lotteryID} and uid !=0 and result= ".self::LOTTERY_RESULT_WAIT)->setField('result',self::LOTTERY_RESULT_OUT);
        //标志活动开奖
        $lotteryM->where("id={$lotteryID}")->setField('resultStatus',1);

        $writeNameNum = $joinM->where("lotteryID={$lotteryID} and uid=0 and result=".self::LOTTERY_RESULT_WIN)->count();
        $lotteryInfo['prizeNum'] =$lotteryInfo['prizeNum']-$writeNameNum;
        if($lotteryInfo['prizeNum'] <=0){
            //公布中奖名单
//            $dataSuccess['winNameList'] = $joinM->where("lotteryID={$lotteryID} and result=2")->field('realName,bindPhone')->select();
//            return $dataSuccess;
        } else{
            $infoStr = $joinM->where("lotteryID={$lotteryID} and uid!=0 and result=".self::LOTTERY_RESULT_OUT)->field('uid,exchangeNum')->select();      //活动报名信息

            $infoUid = array();
            foreach($infoStr as $val){
                $infoUid[] = $val['uid'];
            }
            if($infoStr){
                $winAllStr = $joinM->where("result=".self::LOTTERY_RESULT_WIN." and type={$lotteryInfo['finishType']} and addTime >=".strtotime("-3 month"))->distinct('uid')->field('uid')->select();        //三个月内所有中奖用户
                $payStr = M('u_money_log',null,DB_MAIN_CFG)->where("addOrReduce=2 and addTime >=".strtotime("-1 month"))->distinct('uid')->field('uid')->select();   //一个月内的消费行为
                $winAllUid = array();$payUid = array();
                foreach($winAllStr as $val){
                    $winAllUid[] = $val['uid'];
                }
                foreach($payStr as $val){
                    $payUid[] = $val['uid'];
                }

                //排除3个月内中奖用户
                $uid = array_diff($infoUid,$winAllUid);
                //排除一个月内未有过消费行为用户
                $uid = array_intersect($uid,$payUid);
                if($uid){
                    $joinUid = self::lotteryNameList($uid,$infoStr);
                    if(count($uid) >= $lotteryInfo['prizeNum']){
                       self::randomLottery($lotteryInfo['prizeNum'],$joinUid,$lotteryID);
                    } else if(count($uid)< $lotteryInfo['prizeNum']){
                        $getUid = implode(',',$uid);
                        $joinM->where("lotteryID={$lotteryID} and uid in ({$getUid})")->setField('result',self::LOTTERY_RESULT_WIN);

                        $otherUid = array_diff($infoUid,$uid);
                        $otherUidStr = implode(',',$otherUid);
                        $prizeNum = $lotteryInfo['prizeNum']-count($uid);

                        if(count($otherUid) <= $prizeNum){
                            $joinM->where("lotteryID={$lotteryID} and uid in ({$otherUidStr})")->setField('result',self::LOTTERY_RESULT_WIN);
                        } else {
                            $lotteryUid = self::lotteryNameList($otherUid,$infoStr);
                            self::randomLottery($prizeNum,$lotteryUid,$lotteryID);
                        }
                    }
                } else{
                    $lotteryUid = self::lotteryNameList($infoUid,$infoStr);
                    self::randomLottery($lotteryInfo['prizeNum'],$lotteryUid,$lotteryID);
                }
            }
        }
    }
    /**
     * 生成随机抽奖名单
     * author: wwl <wuwl@soe-soe.com>
     * $uid:满足条件报名用户；$infoStr：其对应的兑换数量
     * Address: 浙江宣逸网络科技有限公司
     */

    public static function lotteryNameList($uid,$infoStr){
        foreach ($uid as $k => $v) {
            $exchangeNum[$k] = $infoStr[$k]['exchangeNum'];
        }
        $joinUid = array();
        foreach ($exchangeNum as $key => $val) {
            for ($i = $val; $i > 0; $i--) {
                $joinUid[] = $uid[$key];
            }
        }
        return $joinUid;
    }
    //随机抽奖
    public static function randomLottery($prizeNum,$joinUid,$lotteryID){
        $joinM = M('point_lottery_join',null,DB_MAIN_CFG);
        shuffle($joinUid);
        $winUid = array_slice($joinUid,0, $prizeNum);
        $getUid = implode(',',$winUid);
        $joinM->where("lotteryID={$lotteryID} and uid in ({$getUid})")->setField('result',self::LOTTERY_RESULT_WIN);       //更新中奖状态

        //发送消息提醒
        $lotteryTitle = M('Point_lottery',null,DB_MAIN_CFG)->where("id={$lotteryID}")->getField('title');
        $title= "系统消息";
        $content = "您参与的活动"."$lotteryTitle"."中奖了，赶快点击前往查看！";
        foreach($winUid as $val){
            NoticeModel::saveNotice(NoticeModel::NOTICE_TYPE_SYSTEM_MSG,NoticeModel::NOTICE_TARGET_POINTLOTTERY,$lotteryID,0,$val,$title,$content);
        }
    }

    //PC积分抽奖首页列表
    public static function getPCLotteryList(){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');

        $nowTime =time();
        $lotteryM = M('point_lottery',null,DB_MAIN_CFG);
        $list = $lotteryM->where("endTime > $nowTime")->order('finishType ASC,period DESC,beginTime ASC')->select();

        if($list){
            foreach($list as $val){
                if($val['beginShowTimestamp'] > $nowTime){
                    $prepareList[] = $val;
                } else{
                    $onlineList[] = $val;
                }
            }
        }
        if($prepareList){
            $pNum = count($prepareList);
            for($i=$pNum;$i>0;$i--){
                if($prepareList[$i]['finishType']==$prepareList[$i-1]['finishType'] && $prepareList[$i]['period']==$prepareList[$i-1]['period']){
                    $prepareList[$i]['period']='';
                }
            }
        }
        if($onlineList){
            $oNum = count($onlineList);
            for($i=$oNum;$i>0;$i--){
                if($onlineList[$i]['finishType']==$onlineList[$i-1]['finishType'] && $onlineList[$i]['period']==$onlineList[$i-1]['period']){
                    $onlineList[$i]['period']='';
                }
            }
        }

        $dataSuccess['prepareList'] = $prepareList;
        $dataSuccess['onlineList'] = $onlineList;

        return $dataSuccess;
    }

    //PC积分抽奖下线列表
    public static function getPCLotteryFinishList($type,$page,$pageSize){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');

        $nowTime = time();
        $lotteryM = M('point_lottery',null,DB_MAIN_CFG);
        if($type == PointLotteryModel::POINTLOTTERY_TIMING){
            $where = "endTime < {$nowTime} and finishType=$type";
        } else {
            $where = "finishType=$type and (endTime < {$nowTime} || joinPeople <= joinTimes)";
        }
        $total = $lotteryM->where($where)->group('period')->field('period')->select();
        $dataSuccess['total'] = count($total);
        $dataSuccess['page'] = $page ? $page : 1;//返回当前页
        $dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
        $dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
        $offset = ($dataSuccess['page']-1)*$pageSize;

        $periodList = $lotteryM->where($where)->limit($offset,$pageSize)->group('period')->order('period DESC')->field('period')->select();
        foreach($periodList as  $val){
            $period[] = $val['period'];
        }
        $period = implode(',',$period);
        $list = $lotteryM->where($where." and period in ({$period})")->order("period DESC,endTime DESC")->select();

        if($list){
            $num = count($list);
            for($i=$num; $i>0; $i--){
                if($list[$i]['period'] == $list[$i-1]['period']){
                    $list[$i]['period'] = '';
                }
            }
        }

        $dataSuccess['list'] = $list;
        return $dataSuccess;
    }
}